/* ClientServerTheard.java 
* Created on Dec 6, 2012 
*@Author: Mr.Viet 
*@Phone: 01683430426 
*@Email: phamvanvietcdhd@gmail.com
*/ 
package com.chat; 

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;

public class ClientServerTheard extends Thread {
	private Socket socket;
	private PrintWriter out;
	private boolean running;
	private BufferedReader buff;
	private String nickName;
	public String getNickName() {
		return nickName;
	}

	public ClientServerTheard(Socket socket) {
		this.socket = socket;
		try {
			out = new PrintWriter(this.socket.getOutputStream());
			buff = new BufferedReader(new InputStreamReader(socket.getInputStream()));
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public static void main(String[] args) {

	}
	@Override
	public void run() {
		while(running){			
			try {
				String str = null;
				while((str=buff.readLine())!=null){
					String[] strItems = str.split("##");
					String type = strItems[0];
					if(type.equals(ServerApp.TYPE_SEND_MESS)){
						String nick = strItems[1];//Lay Nick
						String[] arrnick = nick.split(";");
						String mess = strItems[2];//Lay Message
						//Kiem tra tat ca cac user, neu co nick nao
						//bang voi nick thi gui ve cho user do
						for (int i = 0; i < arrnick.length; i++) {
							for (ClientServerTheard cst : ServerApp.onlineUsers) {
								if(arrnick[i].equals(cst.getNickName())){
									cst.sendMess(mess);
									break;
								}
							}
						}
					}
					else if(type.equals(ServerApp.TYPE_LOGIN_APP)){
						String nick = strItems[1];
						this.nickName = nick;
						//Gui Danh Sach Online Ve
						ServerApp.senOnlineUsers();
					}
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
	public Socket getSocket(){
		return socket;
	}
	public void sendMess(String mess){
		 out.println(mess);
		 out.flush();
	}
}
